package com.sxt.service.impl;

import java.util.Map;
import java.util.UUID;

import org.apache.dubbo.config.annotation.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.demo.trade.model.TradeStatus;
import com.alipay.demo.trade.model.builder.AlipayTradePrecreateRequestBuilder;
import com.alipay.demo.trade.model.result.AlipayF2FPrecreateResult;
import com.alipay.demo.trade.service.AlipayTradeService;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.sxt.config.AlipayConfig;
import com.sxt.model.PayModel;
import com.sxt.service.EgoPayService;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import me.chanjar.weixin.common.api.WxConsts;

@Service
public class PayServiceImpl implements EgoPayService {

	private static Logger log = LoggerFactory.getLogger(PayServiceImpl.class) ;

	@Autowired
	private  AlipayTradeService tradeService  ;

	/**
	 * 只要我们支付成功，支付宝就向 http://www.ego.com/p/order/%s 发起一个post 请求
	 * POST http://www.ego.com/p/order/11111
	 * 支付宝发请求时，http://www.ego.com需要让支付宝能访问成功，需要一个公网地址，我们需要一个网络映射器（支付宝访问一个特定的公网地址，该公网服务器里面有个软件，把该请求转发到你的电脑上面）
	 */
	private static final String NOTIFY_URL = "http://ltd.vipgz2.idcfengye.com/p/order/notify/%s" ; // %s代表我们的订单编号 

	@Autowired
	private AlipayClient alipayClient ;

	@Autowired
	private WxPayService wxPayService ;
	/**
	 * 使用订单的一些参数得到可以支付的url 地址
	 */
	@Override
	public String aliPay(PayModel model) {
		Integer payType = model.getPayType(); // 1 扫码  2 网页支付
		switch (payType) {
		case 1: // 扫描支付
			return getQrCode(model) ;
		case 2: // 网页支付
			return getFormHtml(model);
		default:
			throw new RuntimeException("不支持的支付类型!") ;
		}

	}
	private String getFormHtml(PayModel model) {
		//设置请求参数
		AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
		alipayRequest.setReturnUrl(AlipayConfig.return_url);
		alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("out_trade_no", model.getOutTradeNo()) ;
		jsonObject.put("total_amount", model.getTotalAmount()) ;
		jsonObject.put("subject", model.getSubject()) ;
		jsonObject.put("body", model.getBody()) ;
		jsonObject.put("product_code", "FAST_INSTANT_TRADE_PAY") ;
		alipayRequest.setBizContent(jsonObject.toString());  // 直接得到json的值
		System.out.println(jsonObject.toString());
		//请求
		try {
			String result = alipayClient.pageExecute(alipayRequest).getBody(); // 类似给支付宝发Http 请求
			return result ;
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
		return null;
	}

	private String getQrCode(PayModel model) {
		// 创建扫码支付请求builder，设置请求参数对象
		AlipayTradePrecreateRequestBuilder builder = new AlipayTradePrecreateRequestBuilder()
				.setSubject(model.getSubject())
				.setTotalAmount(model.getTotalAmount())
				.setOutTradeNo(model.getOutTradeNo())
				.setUndiscountableAmount(model.getUndiscountableAmount())
				.setSellerId(model.getSellerId())
				.setBody(model.getBody())
				.setOperatorId(model.getOperatorId())
				.setStoreId(model.getStoreId())
				.setTimeoutExpress(model.getTimeoutExpress())
				.setNotifyUrl(String.format(NOTIFY_URL, model.getOutTradeNo())) ;//支付宝服务器主动通知商户服务器里指定的页面http路径,根据需要设置
		AlipayF2FPrecreateResult tradePrecreate = tradeService.tradePrecreate(builder); // 类似我们给支付宝发了Http 请求
		if(tradePrecreate.getTradeStatus()==TradeStatus.SUCCESS) { // 预创建支付链接成功
			AlipayTradePrecreateResponse response = tradePrecreate.getResponse();
			String qrCode = response.getQrCode(); // 得到二维码的地址
			log.info("预生成支付链接成功{}",qrCode);
			return qrCode ;
		}else {
			AlipayTradePrecreateResponse response = tradePrecreate.getResponse();
			log.info("预生成支付链接失败，原因为{}",response.getMsg());
			return null;
		}
	}
	@Override
	public String wechatPay(PayModel model) {
		WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
		request.setAppid("wx6e9638417bfflcl3");
		request.setMchId("1487990592");
		request.setTradeType(WxPayConstants.TradeType.JSAPI); // 小程序的支付
		request.setNotifyUrl("http://www.egoshop.com");
		request.setSignType(WxPayConstants.SignType.MD5);

		request.setNonceStr(UUID.randomUUID().toString());
		request.setBody(model.getBody());
		request.setAttach(model.getSubject());
		request.setOpenid("olkQuwgkczuB_VOX9bBSTFb8SG9Q");
		request.setTotalFee(12312);
		request.setOutTradeNo(model.getOutTradeNo());
		request.setSpbillCreateIp("127.0.0.1");
		request.setSubAppId("wx6e9638417bfflcl3");
		request.setSubMchId("1487990592");
		try {
			Object createOrder = wxPayService.createOrder(request) ;
			return JSONUtil.toJsonStr(createOrder) ;
		} catch (WxPayException e) {
			e.printStackTrace();
		} // 所有的下单都在这里面完成
		return null;
	}
	@Override
	public boolean checkRASSign(Map<String, String> params) {
		try {
			//调用SDK验证签名
			boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
			return signVerified ;
		} catch (AlipayApiException e) {
			e.printStackTrace();
			return false ;
		} 
	}
}
